#include "membittable.h"
#include "bithashtablehandle.h"
#include <errno.h>
#include "config.h"

MemBitTable::MemBitTable()
    : m_tableSize(TABLE_SIZE)
    , m_addr(NULL)
    , m_hashHandle(NULL)
{
}

MemBitTable::~MemBitTable()
{
    if (m_addr != NULL)
        free(m_addr);

    if (m_hashHandle != NULL)
        delete m_hashHandle;
}

bool MemBitTable::init()
{
    if (m_hashHandle != NULL || m_addr != NULL)
        return false;

    m_addr = (unsigned char *)malloc(m_tableSize);
    memset(m_addr, 0, m_tableSize);

    if (m_hashHandle == NULL)
        m_hashHandle = new BitHashTableHandle(this);

    return true;
}

bool MemBitTable::getBitValue(unsigned long pos)
{
    unsigned char* p = m_addr;
    p += pos/8;
    unsigned char mask = 0x01 << pos%8;
    return (((*p) & mask)>>pos%8);
}

void MemBitTable::setBitValue(unsigned long pos)
{
    unsigned char* p = m_addr;
    p += pos/8;
    unsigned char mask = 0x01 << pos%8;
    *p |= mask;
}

void MemBitTable::clearBitValue(unsigned long pos)
{
    unsigned char* p = m_addr;
    p += pos/8;
    unsigned char mask = !(0x01 << pos%8);
    *p &= mask;
}

void MemBitTable::clear()
{
    memset(m_addr, 0, m_tableSize);
}

